package com.compomics.prioritizer.general.gui;

import com.compomics.prioritizer.db.accessors.User;
import com.compomics.prioritizer.db.accessors.Project;
import com.compomics.prioritizer.db.accessors.Label;
import com.compomics.prioritizer.general.ConnectablePriorityProject;
import com.compomics.prioritizer.general.ConnectionDialog;
import com.compomics.prioritizer.general.PrioritizerSingelton;
import com.compomics.prioritizer.general.gui.AddInstrumentGui;

import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.mail.internet.MimeMessage;
import javax.mail.MessagingException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.*;
import java.util.HashMap;
import java.util.Collection;

import org.masukomi.aspirin.core.MailWatcher;
import org.apache.mailet.MailAddress;

/**
 * Created by IntelliJ IDEA.
 * User: Niklaas Colaert
 * Date: 31-okt-2008
 * Time: 9:13:47
 * To change this template use File | Settings | File Templates.
 */
public class PriorityGUI extends JFrame implements ConnectablePriorityProject, MailWatcher {
    private JPanel createProjectPanel;
    private JButton createButton;
    private JButton viewButton;
    private JPanel jPanContent;
    private JButton acceptButton;
    private JButton createButton1;
    private JButton addUserbtn;
    private JButton addANewInstrumentButton;
    private JLabel lblAccept;
    private JButton addNewLabelButton;
    private JTextField txtLabel;

    //the connections
    public Connection iConnPriority;
    /*
     * The user role
     * 1 =  normal user
     * 2 =  user that may change priorities
     * 3 =  operator
     * 4 =  developer
     */
    public int iRole = -1;
    private User iUser;
    private Project[] iProjects;

    private PrioritizerSingelton iPrioritizerSingelton;

    public PriorityGUI() {
        super("Prioritizer");
        $$$setupUI$$$();
        iPrioritizerSingelton = PrioritizerSingelton.getInstance();
        this.getConnection();
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent evt) {
                close();
            }
        });

        createButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                CreateProject createProject = new CreateProject(iConnPriority, iUser);
                createProject.setVisible(true);
            }
        });
        setContentPane(jPanContent);


        acceptButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                findProjects();
                AcceptProject accept = new AcceptProject(iConnPriority, iUser, iProjects);
                accept.setVisible(true);
            }
        });
        viewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                PriorityListGUI list = new PriorityListGUI(iConnPriority, iUser);
                list.setVisible(true);
            }
        });
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation((screen.width / 3), (screen.height / 4));
        this.setSize(300, 300);
        this.setVisible(true);
        createButton1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                CreateProtocolGui protocol = new CreateProtocolGui(iConnPriority);
                protocol.setVisible(true);
            }
        });
        addUserbtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                AddUserGui userAdd = new AddUserGui(iConnPriority);
                userAdd.setVisible(true);
            }
        });
        addANewInstrumentButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                AddInstrumentGui addIns = new AddInstrumentGui(iConnPriority);
                addIns.setVisible(true);
            }
        });
        addNewLabelButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                addNewLabel();
            }
        });

        //only show the add user button and create protocol button to the developers
        if (iRole == 4) {
            addUserbtn.setVisible(true);
            createButton1.setVisible(true);
            addANewInstrumentButton.setVisible(true);
            addNewLabelButton.setVisible(true);
            txtLabel.setVisible(true);
        } else {
            addUserbtn.setVisible(false);
            addANewInstrumentButton.setVisible(false);
            createButton1.setVisible(false);
            addNewLabelButton.setVisible(false);
            txtLabel.setVisible(false);
        }
        // only show the accept button to the administrator
        if (iRole == 2) {
            acceptButton.setVisible(true);
            lblAccept.setVisible(true);
        } else {
            acceptButton.setVisible(false);
            lblAccept.setVisible(false);
        }
    }

    public void passConnection(Connection connection, String s) {
        this.iConnPriority = connection;
        this.getUserRole();
    }


    private void addNewLabel() {
        String lLabel = txtLabel.getText();
        if (lLabel.equalsIgnoreCase("")) {
            JOptionPane.showMessageDialog(this, "No label was found", "??????????", JOptionPane.INFORMATION_MESSAGE);
            return;
        } else {
            HashMap hm = new HashMap();
            hm.put(Label.NAME, lLabel);
            Label lNewLabel = new Label(hm);
            try {
                lNewLabel.persist(iConnPriority);
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(this, new String[]{"Unable to store new label:  ", e.getMessage()}, "Error!", JOptionPane.ERROR_MESSAGE);
                return;
            }
            JOptionPane.showMessageDialog(this, "New label was Stored", "Stored", JOptionPane.INFORMATION_MESSAGE);
        }

    }

    private void findProjects() {
        try {
            iProjects = Project.getAllNewProjects(iConnPriority);
            if (iProjects.length == 0) {
                JOptionPane.showMessageDialog(this, "No new projects found!", "No projects found", JOptionPane.INFORMATION_MESSAGE);
                this.close();
            }
        } catch (SQLException sqle) {
            JOptionPane.showMessageDialog(this, new String[]{"Unable to find instruments:  ", sqle.getMessage()}, "Error!", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void getUserRole() {
        String user = null;
        try {
            iPrioritizerSingelton = PrioritizerSingelton.getInstance();
            PreparedStatement prep = iConnPriority.prepareStatement("select user()");
            ResultSet rs = prep.executeQuery();
            while (rs.next()) {
                user = rs.getString(1);
            }
            user = user.substring(0, user.indexOf("@"));
            rs.close();
            prep.close();
            iUser = User.getUserByName(iConnPriority, user);
            iPrioritizerSingelton.setUser(iUser);
            if (iUser == null) {
                JOptionPane.showMessageDialog(this, "Unable to find user: Create a user! Or go to the developer.", "Error!", JOptionPane.ERROR_MESSAGE);
                iRole = 4;
            } else {
                iRole = iUser.getRole();
            }


        } catch (SQLException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }

    /**
     * This method creates a dialog which handles the DB connection.
     */
    private void getConnection() {
        ConnectionDialog cd = new ConnectionDialog(this, this, "Establish DB connection", "priority.properties");
        cd.setVisible(true);
    }


    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (InstantiationException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (IllegalAccessException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (UnsupportedLookAndFeelException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
        PriorityGUI gui = new PriorityGUI();
    }

    public void passConnectionPriority(Connection connection) {
        this.iConnPriority = connection;
        this.getUserRole();
    }

    /**
     * This method is called when the frame is closed. It shuts down the JVM.
     */
    private void close() {
        if (iConnPriority != null) {
            try {
                iConnPriority.close();
                System.out.println("\n\nDB connection closed.\n\n");
            } catch (SQLException sqle) {
                System.err.println("\n\nUnable to close DB connection!\n\n");
            }
        }
        System.exit(0);
    }

    public void deliverySuccess(MimeMessage mimeMessage, Collection collection) {
        try {
            System.out.println(mimeMessage.getSubject() + "     ok     ");
        } catch (MessagingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public void deliveryFailure(MimeMessage mimeMessage, Collection collection) {
        try {
            System.out.println(mimeMessage.getSubject() + "   not  ok  !!!!!!!!!!!!!   ");
        } catch (MessagingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public void deliverySuccess(MimeMessage mimeMessage, MailAddress mailAddress) {
        try {
            System.out.println(mimeMessage.getSubject() + "     ok     ");
        } catch (MessagingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    public void deliveryFailure(MimeMessage mimeMessage, MailAddress mailAddress) {
        try {
            System.out.println(mimeMessage.getSubject() + "   not  ok  !!!!!!!!!!!!!   ");
        } catch (MessagingException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }

    /**
     * Method generated by IntelliJ IDEA GUI Designer
     * >>> IMPORTANT!! <<<
     * DO NOT edit this method OR call it in your code!
     *
     * @noinspection ALL
     */
    private void $$$setupUI$$$() {
        jPanContent = new JPanel();
        jPanContent.setLayout(new GridBagLayout());
        createProjectPanel = new JPanel();
        createProjectPanel.setLayout(new GridBagLayout());
        GridBagConstraints gbc;
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.BOTH;
        jPanContent.add(createProjectPanel, gbc);
        createProjectPanel.setBorder(BorderFactory.createTitledBorder(null, "Welcome, ", TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.ABOVE_TOP, new Font(createProjectPanel.getFont().getName(), createProjectPanel.getFont().getStyle(), createProjectPanel.getFont().getSize())));
        final JLabel label1 = new JLabel();
        label1.setText("Create a project");
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1.0;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.insets = new Insets(5, 5, 5, 5);
        createProjectPanel.add(label1, gbc);
        createButton = new JButton();
        createButton.setText("Create");
        gbc = new GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        createProjectPanel.add(createButton, gbc);
        final JLabel label2 = new JLabel();
        label2.setText("View the priority list");
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.weightx = 1.0;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.insets = new Insets(5, 5, 5, 5);
        createProjectPanel.add(label2, gbc);
        lblAccept = new JLabel();
        lblAccept.setText("Accept a project");
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.weightx = 1.0;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.insets = new Insets(5, 5, 5, 5);
        createProjectPanel.add(lblAccept, gbc);
        viewButton = new JButton();
        viewButton.setText("View");
        gbc = new GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        createProjectPanel.add(viewButton, gbc);
        acceptButton = new JButton();
        acceptButton.setText("Accept");
        gbc = new GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 2;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        createProjectPanel.add(acceptButton, gbc);
        createButton1 = new JButton();
        createButton1.setText("Create a new protocol");
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        createProjectPanel.add(createButton1, gbc);
        addUserbtn = new JButton();
        addUserbtn.setText("Add a new user");
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        createProjectPanel.add(addUserbtn, gbc);
        addANewInstrumentButton = new JButton();
        addANewInstrumentButton.setText("Add a new instrument");
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 5;
        gbc.gridwidth = 2;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        createProjectPanel.add(addANewInstrumentButton, gbc);
        addNewLabelButton = new JButton();
        addNewLabelButton.setText("Add new label");
        gbc = new GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 6;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        createProjectPanel.add(addNewLabelButton, gbc);
        txtLabel = new JTextField();
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 6;
        gbc.anchor = GridBagConstraints.WEST;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        createProjectPanel.add(txtLabel, gbc);
    }

    /**
     * @noinspection ALL
     */
    public JComponent $$$getRootComponent$$$() {
        return jPanContent;
    }
}
